<?php
declare (strict_types = 1);
namespace come;

class View
{
    // 视图实例
    protected static $instance;

    // 模板变量
    protected $data = [];

    /**
     * 初始化视图
     * @return View
     */
    public static function instance()
    {
        if (is_null(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * 模板变量赋值
     * @access public
     * @param mixed $name  变量名
     * @param mixed $value 变量值
     * @return $this
     */
    public function assign($name, $value = '')
    {
        if (is_array($name)) {
            $this->data = array_merge($this->data, $name);
        } else {
            $this->data[$name] = $value;
        }
        return $this;
    }

    /**
     * 渲染模板输出
     * @param string $template
     */
    public function display($template = '')
    {
        return $this->fetch($template = '');
    }

    /**
     * 使用指定模板
     * @param string $template
     */
    private function fetch($template = '')
    {
        $request = Request::instance();
        if(empty($template)){
            $template = APP_PATH;
            if($request->module_name){
                $template .= $request->module_name . DS;
            }
            $template .= 'view' . DS . $request->controller_name . DS . $request->action_name . '.php';
        }

        if(file_exists($template)){
            $view = Config::get('view');
            if($view['template']==true){
                $cache_file_name = TEMPLATE_PATH.$request->module_name."_".$request->controller_name."_".$request->action_name . '.php';
                if(false/*file_exists($cache_file_name)*/){
                    extract($this->data);
                    include_once $cache_file_name;
                }else{
                    $view_contents = file_get_contents($template);

                    Template::parse($view_contents);

                    if(!is_dir(TEMPLATE_PATH)){
                        mkdir(RUNTIME_PATH);
                        mkdir(TEMPLATE_PATH);
                    }

                    file_put_contents($cache_file_name,$view_contents);
                    if(file_exists($cache_file_name)){
                        extract($this->data);
                        include_once $cache_file_name;
                    }else{
                        file_put_contents($cache_file_name,$view_contents);
                        Debug::dump('模板缓存【' . $cache_file_name . '】生成失败');
                    }
                }
            }else{
                extract($this->data);
                include_once $template;
            }
        }else{
            Debug::dump('模板文件【' . $template . '】不存在');
        }
    }
}
